const ELEMENT_NUMBER=10;//每次至多十个活动
const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});
const db = cloud.database();
const queryOngoingActivities=async(event)=>{
  const now=new Date();
  const result=await db.collection("Activity_Information").where({
    ActivityPublishTime: db.command.lte(now),//当前已发布
    RegistrationEndTime: db.command.gte(now),//当前未结束报名
    Status: 'Published'//状态是已发布
  }).orderBy('ActivityPublishTime','desc').skip((event.tableNumber-1)*ELEMENT_NUMBER).limit(ELEMENT_NUMBER).get();
  if (result.data.length > 0) {
    // 把数据库结果转换成结构化对象数组
   const activities = result.data.map(item => ({
      activityID: item._id,
      activityName: item.ActivityName,
      activityImage: item.ActivityImageURL,
      activityTime: [],
      activityLocation: item.ActivityLocation,
    }));
    await Promise.all(
      activities.map(async element => {
        const groupResult = await db.collection("Activity_Group_Information")
          .where({ ActivityID: element.activityID })
          .orderBy('GroupStartTime','asc')
          .get();
        element.activityTime = groupResult.data.map(g => ({
          startTime:g.GroupStartTime,
          endTime: g.GroupEndTime
        }));
      })
    );    
    return {
      activities: activities
    };
  }else{
      return {activities: []};
  }
}
exports.main = async (event, context) => {
  return await queryOngoingActivities(event);
};